<?php

namespace app\common\repositories\payment;

use app\common\services\WechatService;
use app\common\dao\payment\PaymentLogDao;
use app\common\repositories\BaseRepository;

/**
 * Class PaymentLogRepository
 * @mixin PaymentLogDao
 */
class PaymentLogRepository extends BaseRepository
{

    const USE_TYPE = [
        1 => '余额充值',
        2 => '订单支付',
        3 => '设备预存',
        4 => '账单支付'
    ];

    public function __construct(PaymentLogDao $dao)
    {
        $this->dao = $dao;
    }

    public function getPropertyList(array $where, $page, $limit, int $propertyId = null)
    {
        $query = $this->dao->search($where, $propertyId);
        $count = $query->count();
        $list = $query->page($page, $limit)
            ->order('id', 'desc')
            ->select();
        return compact('count', 'list');
    }

    /**
     * 支付成功
     * @param $payLogId
     * @param $transactionId
     * @return false|void
     * @throws \think\db\exception\DataNotFoundException
     * @throws \think\db\exception\DbException
     * @throws \think\db\exception\ModelNotFoundException
     *
     * @author Amos
     * 2024-06-15 11:24
     */
    public function paySuccess($payLogId, $transactionId = '')
    {
        $payLogInfo = $this->dao->get($payLogId);
        if (!$payLogInfo) {
            return false;
        }
        // 已处理过不重复处理
        if ($payLogInfo['status'] != 1) {
            return false;
        }

        $this->dao->update($payLogId, [
            'status' => 2,
            'transaction_id' => $transactionId,
            'notify_time' => date('Y-m-d H:i:s')
        ]);

        $params = $payLogInfo['params'];
        $amount = $payLogInfo['amount'];
        if (isset($params['amount']) && $params['amount'] > 0) {
            $amount = $params['amount'];
        }
        switch ($payLogInfo['use_type']) {
            case 1:
                ## 余额充值
                break;
            case 2:
                ## 订单支付
                break;
            case 3:
                ## 设备预存
                /** @var PropertyContractDeviceRepository $contractDeviceRepository */
                $contractDeviceRepository = app()->make(PropertyContractDeviceRepository::class);
                $contractDeviceInfo = $contractDeviceRepository->get($params['contract_device_id']);
                if ($contractDeviceInfo) {
                    $payType = $params['pay_type'] == 'wechat' ? '微信' : ($params['pay_type'] == 'alipay' ? '支付宝' : '');
                    $contractDeviceRepository->balanceChange($contractDeviceInfo['id'], $payLogInfo['user_id'], 1, $amount, $payType . '预存');

                    ## 添加物业流水  device_type
                    /** @var PropertyFinanceRepository $propertyFinanceRepository */
                    $propertyFinanceRepository = app()->make(PropertyFinanceRepository::class);
                    $propertyFinanceRepository->addInfo($contractDeviceInfo['company_id'], $contractDeviceInfo['property_id'], [
                        'is_type' => 3,
                        'amount' => $amount,
                        'contract_id' => $contractDeviceInfo['contract_id'],
                        'device_id' => $contractDeviceInfo['device_id'],
                        'device_type' => $contractDeviceInfo['device_type'],
                        'room_id' => $contractDeviceInfo['room_id'],
                        'remark' => $payLogInfo['remark'] ?? '',
                        'pay_type' => ($params['pay_type'] == 'wechat' ? '1' : ($params['pay_type'] == 'alipay' ? '2' : '')),
                    ]);

                }

                break;
            case 4:
                ## 账单汇总支付
                /** @var PropertyBillRepository $propertyBillRepository */
                $propertyBillRepository = app()->make(PropertyBillRepository::class);
                $propertyRoomBillInfo = $propertyBillRepository->get($params['bill_id']);
                if ($propertyRoomBillInfo) {
                    $payType = $payLogInfo['pay_type'] == 'wechat' ? 1 : ($payLogInfo['pay_type'] == 'alipay' ? 2 : '');
                    $payType = $payType ?: 1;

                    $propertyBillRepository->billPaySuccess($propertyRoomBillInfo, $payLogInfo['user_id'], 1, $payType, null, $amount);

                    ## 添加物业流水
                    /** @var PropertyFinanceRepository $propertyFinanceRepository */
                    $propertyFinanceRepository = app()->make(PropertyFinanceRepository::class);
                    $propertyFinanceRepository->addInfo($propertyRoomBillInfo['company_id'], $propertyRoomBillInfo['property_id'], [
                        'is_type' => 3,
                        'amount' => $amount,
                        'contract_id' => $propertyRoomBillInfo['contract_id'],
                        'room_id' => $propertyRoomBillInfo['room_id'],
                        'pay_type' => $payType,
                    ]);

                }
                break;
            case 5:
                ## 账单明细支付

                break;
        }
    }

    /**
     * 支付失败
     * @param int $payLogId
     * @param string $failMsg
     * @return int
     * @throws \think\db\exception\DbException
     *
     * @author Amos
     * 2024-06-15 11:25
     */
    public function payFail(int $payLogId, string $failMsg = '')
    {
        return $this->dao->update($payLogId, [
            'status' => 3,
            'fail_msg' => $failMsg,
            'notify_time' => date('Y-m-d H:i:s')
        ]);
    }

    /**
     * 创建支付
     *
     * @param string $clientType 客户端类型
     * @param string $payType 支付类型
     * @param int $useType 操作类型
     * @param int $userId 会员id
     * @param float $amount 支付金额
     * @param string $remark 备注
     * @param array $params 其他参数
     * @param array $payeeInfo 收款方信息 ['to_user_id' => '收款用户ID','property_id' => '物业ID']
     * @return array
     */
    public function createPay(int $propertyId, $clientType, $payType, $useType, $userId, $amount, $remark, $params, $payeeInfo = [])
    {
        $payInfo = $this->dao->addLog($propertyId, $clientType, $payType, $useType, $userId, $amount, $remark, $params, $payeeInfo);

        $returnData = [
            'pay_log_id' => $payInfo['id']
        ];
        $payMethod = $params['pay_type'] ?? '';
        // 手机app使用微信支付打开小程序支付
        if ($clientType == 'android' && $payMethod == 'wechat') {
            $wechatServer = WechatService::init($propertyId);
            $url = $wechatServer->miniScheme('pages/tenantbox/billbox/appwechat', 'payLogId=' . $payInfo['id'] . '&amount=' . $amount);
            $returnData['scheme_url'] = $url;
        }

        return $returnData;
    }

    /**
     * 创建支付支付二维码
     * @param string $clientType 客户端类型
     * @param string $payType 支付类型
     * @param int $useType 操作类型
     * @param int $userId 会员id
     * @param float $amount 支付金额
     * @param string $remark 备注
     * @param array $params 其他参数
     * @param array $payeeInfo 收款方信息 ['to_user_id' => '收款用户ID','property_id' => '物业ID']
     * @return array
     *
     * @author Amos
     * 2024-06-15 11:32
     */
    public function createPayQrcode($propertyId, $clientType, $payType, $useType, $userId, $amount, $remark, $params, $payeeInfo = [])
    {
        $payInfo = $this->dao->addLog($propertyId, $clientType, $payType, $useType, $userId, $amount, $remark, $params, $payeeInfo);

        $domain = request()->domain(true);
        $wechatServer = WechatService::init($propertyId);
        $url = $wechatServer->generateUrllink('pages/tenantbox/billbox/appwechat', 'payLogId=' . $payInfo['id'] . '&amount=' . $amount);
        $returnData = [
            'qrcode_url' => $domain . '/qrcode/get?text=' . $url
        ];
        return $returnData;
    }
}